'use strict';

//闭包限定命名空间
(function ($) {
    var socket;
    var connected=false;
    var channelName="chat";
    var msgListener=[];

    function initWsSocket(){
        if(socket!=undefined && socket!=null){
            return socket;
        }
        var scheme = document.location.protocol == "https:" ? "wss" : "ws";
        var port = document.location.port ? (":" + document.location.port) : "";
        // see app.Get("/echo", ws.Handler()) on main.go
        var wsURL = scheme + "://" + document.location.hostname + port+"/echo";

        socket = new Ws(wsURL);
        socket.OnConnect(function (data) {
            connected=true;
            $.showlog("OnConnect",data);
            $.sendMessage({code:'1000',msg:'注册客户端成功'})
        });

        socket.OnDisconnect(function (data) {
            connected=false;
            socket=undefined;
            $.showlog("OnDisconnect",data);
        });

        // read events from the server
        socket.On(channelName, function (data) {
             $.showlog("read msg from "+channelName, data)
        });
        for (var i = 0; i < msgListener.length; i++) {
            var callback=  msgListener[i];
            if(callback===undefined || callback===null){
                return;
            }
            socket.On(channelName, function (data) {
                callback(socket,data);
            });
        }
        msgListener=[];
    }

    $.registerCallback=function(callback){
        if(callback===undefined || callback===null){
            return;
        }
        if(socket===undefined || socket==null){
            msgListener.push(callback);
            return;
        }
        msgListener=[];
        // read events from the server
        socket.On(channelName, function (data) {
            callback(socket,data);
        });
    };

    $.registerCloseCallback=function(callback){
        if(callback===undefined || callback===null){
            return;
        }
        var closeCallback=function (client,data) {
           callback(client,data);
           client.Disconnect()
        };
        if(socket===undefined || socket==null){
            msgListener.push(closeCallback);
            return;
        }
        msgListener=[];
        // read events from the server
        socket.On(channelName, function (data) {
            closeCallback(socket,data);
        });
    };

    //data:{code:1001,msg:'nihaoya'}
    $.sendMessage=function (data) {
        var client= initWsSocket();
        client.Emit(channelName, data);
    };
    $.sendMsg=function (code,msg,data) {
        $.sendMessage({code:code,msg:msg,data:data})
    }
})(window.jQuery);
